import json
from django.http.response import JsonResponse
from .inventoryController import BaseInventory
from .runnerController import CommandRunner, AdHocRunner
from django.views import View
import unittest
import sys

sys.path.insert(0, "../..")


class TestAdHocRunner(unittest.TestCase):
    def setUp(self):
        host_data = [
            {
                "hostname": "testserver",
                "ip": "192.168.56.102",
                "port": 22,
                "username": "root",
                "password": "123456",
            },
        ]
        inventory = BaseInventory(host_data)
        self.runner = AdHocRunner(inventory)

    def test_run(self):
        tasks = [
            {"action": {"module": "shell", "args": "ls"}, "name": "run_cmd"},
            {"action": {"module": "shell", "args": "whoami"}, "name": "run_whoami"},
        ]
        ret = self.runner.run(tasks, "all")
        print(ret.results_summary)
        print(ret.results_raw)


class TestCommandRunner(unittest.TestCase):

    def setUp(self):
        host_data = [
            {
                "hostname": "testserver",
                "ip": "192.168.56.102",
                "port": 22,
                "username": "root",
                "password": "123456",
            },
        ]
        inventory = BaseInventory(host_data)
        self.runner = CommandRunner(inventory)

    def test_execute(self):
        res = self.runner.execute('ls', 'all')
        print(res.results_summary)
        print(res.results_raw)


# if __name__ == "__main__":
#     print("xxx")
#     unittest.main()

class runAdhoc(View):
    @staticmethod
    def post(request):
        boby = json.loads(request.body)
        print(boby)
        # {
        #     "hostname": "testserver",
        #     "ip": "192.168.56.102",
        #     "port": 22,
        #     "username": "root",
        #     "password": "123456",
        # }
        host_data = []
        host_data.append(boby)

        inventory = BaseInventory(host_data)
        runner = CommandRunner(inventory)
        # 获取执行的命令
        cmd = boby["beshell"]
        res = runner.execute(cmd)
        # 输出执行结果
        print(res.results_summary)
        print(res.results_raw)
        if (res):
            response = {'code': 200, 'msg': "运行成功"}

            return JsonResponse(response)
        else:
            response = {'code': 201, 'msg': "运行失败"}
            return JsonResponse(response)
